package org.hibernate.tutorial.util;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static Session getSession() {
    	return getSessionFactory().openSession(); //.getCurrentSession();
    }
    
    public static void add(Object obj) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(obj);
			tx.commit();			
		} catch (HibernateException e) {
			if (tx != null) 
				tx.rollback();
			throw e;
		} finally {
			if(s != null) 
				s.close();
		}    	
    }
    
    public static void update(Object obj) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.update(obj);
			tx.commit();			
		} catch (HibernateException e) {
			if (tx != null) 
				tx.rollback();
			throw e;
		} finally {
			if(s != null) 
				s.close();
		}    	
    }
    
    public static void delete(Object obj) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(obj);
			tx.commit();			
		} catch (HibernateException e) {
			if (tx != null) 
				tx.rollback();
			throw e;
		} finally {
			if(s != null) 
				s.close();
		}    	
    }   
    
	public static Object get(Class clazz, Serializable id) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Object obj = s.get(clazz, id);
			return obj;			
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (s != null) s.close();
		}
	}   
	
	public static List<Object> findAll(Class clazz){
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from " + clazz.getName();
			Query q = s.createQuery(hql);
			return q.list();		
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (s != null) s.close();
		}		
	}

}